<template>
    <view class="index">
        <view v-for="(item, index) in state.pages" :key="index">
            <template v-if="item.name == 'search'">
                <w-search :content="item.content" :styles="item.styles" />
            </template>
            <template v-if="item.name == 'banner'">
                <w-banner :content="item.content" :styles="item.styles" />
            </template>
            <template v-if="item.name == 'nav'">
                <w-nav :content="item.content" :styles="item.styles" />
            </template>
        </view>
        <view class="article" v-if="state.article.length">
            <view class="flex items-center article-title mx-[20rpx] my-[30rpx] text-2xl font-medium">
                最新资讯
            </view>
            <news-card v-for="item in state.article" :key="item.id" :news-id="item.id" :item="item" />
        </view>
        <tabbar />
    </view>
</template>

<script setup lang="ts">
import { getIndex } from '@/api/shop'
import { reactive } from 'vue'
import { mnpLogin } from '@/api/account'
import { onLoad } from '@dcloudio/uni-app'

const state = reactive<{
    pages: any[]
    article: any[]
}>({
    pages: [],
    article: []
})
const getData = async () => {
    const data = await getIndex()
    state.pages = JSON.parse(data?.page?.data)
    state.article = data.article
}

const wxLogin = async (order_sn: string) => {
    // #ifdef MP-WEIXIN

    try {
        const { code }: any = await uni.login({
            provider: 'weixin'
        })
        const data = await mnpLogin({
            code: code,
            order_sn: order_sn
        })

        // #ifdef  MP-WEIXIN
        if (data?.order_info) {
            uni.requestPayment({
                provider: 'wxpay',
                timeStamp: data?.order_info?.timeStamp,
                nonceStr: data?.order_info?.nonceStr,
                package: data?.order_info?.package,
                signType: data?.order_info?.signType,
                paySign: data?.order_info?.paySign,
                success: (res) => {
                    uni.redirectTo({
                        url: '/pages/webview/webview?url=' + encodeURIComponent(data?.url)
                    })
                },
                fail: (res) => {
                    uni.redirectTo({
                        url: '/pages/webview/webview?url=' + encodeURIComponent(data?.url)
                    })
                }
            })
        }
        // #endif
        console.log(data)
    } catch (error: any) {
        uni.hideLoading()
        uni.$u.toast(error)
    }
    // #endif
}

getData()

onLoad((options: any) => {
    console.log(options)
    wxLogin(options.order_sn === 'undefined' ? '' : options.order_sn)
})
</script>

<style lang="scss">
.article-title {
    &::before {
        content: '';
        width: 8rpx;
        height: 34rpx;
        display: block;
        margin-right: 10rpx;
        background: $u-type-primary;
    }
}
</style>
